﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPFMitsuControlsv2;
using System.Windows;
using System.ComponentModel;
using Microsoft.Surface.Presentation.Controls.Primitives;
using System.Reflection;

namespace BookSurfaceDemoApp
{

    [TemplatePart(Name = CustomBookItem.ElementPopup, Type = typeof(SurfacePopup))]
    public class CustomBookItem : BookItem
    {
        const string ElementPopup = "PART_Popup";

        DateTime? _lastEtiquetteRefresh;
        readonly TimeSpan _etiquetteRefresh = TimeSpan.FromMilliseconds(50);
        bool _refreshCompleted = true;

        SurfacePopup _popup;

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            this.LayoutUpdated += new EventHandler(CustomBookItem_LayoutUpdated);
        }

        void CustomBookItem_LayoutUpdated(object sender, EventArgs e)
        {
            if (IsPopupOpen)
            {
                var now = DateTime.Now;
                if (_lastEtiquetteRefresh == null)
                    _lastEtiquetteRefresh = now;
                else if (_refreshCompleted && now - _lastEtiquetteRefresh > _etiquetteRefresh)
                {

                    _refreshCompleted = false;

                    var invoke = this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        // call reposition internal method to move the popup to the right place
                        _popup.GetType().InvokeMember("Reposition",
                            BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
                            Type.DefaultBinder, _popup, null);

                    }), System.Windows.Threading.DispatcherPriority.Background, null);
                    invoke.Completed += (s, ee) => { _refreshCompleted = true; _lastEtiquetteRefresh = now; };

                }
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (_popup != null)
                _popup.Closed -= new EventHandler(_popup_Closed);

            _popup = GetTemplateChild(ElementPopup) as SurfacePopup;
            if (_popup != null)
                _popup.Closed += new EventHandler(_popup_Closed);
        }

        void _popup_Closed(object sender, EventArgs e)
        {
            IsPopupOpen = false;
        }

        protected override void HandleTap()
        {
            if (!IsSelected)
                NavigateToThisBookItem();
            else
                BeginEdit();
        }

        public override void BeginEdit()
        {
            IsPopupOpen = true;
        }

        public bool IsPopupOpen
        {
            get { return (bool)GetValue(IsPopupOpenProperty); }
            set { SetValue(IsPopupOpenProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsPopupOpen.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsPopupOpenProperty =
            DependencyProperty.Register("IsPopupOpen", typeof(bool), typeof(CustomBookItem), new UIPropertyMetadata(false, OnIsPopupOpenChanged));

        private static void OnIsPopupOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var bi = d as CustomBookItem;
            bool val = (bool)e.NewValue;

            if (bi._popup != null && bi._popup.IsOpen != val) 
                bi._popup.IsOpen = val;
        }

        protected override void UnFocus()
        {
            IsPopupOpen = false;
        }

    }
}
